import React, { useEffect, useRef } from 'react';
import { Modal, Button, Space, Typography, Card, Spin, Tabs, message } from 'antd';
import JsBarcode from 'jsbarcode';
import { BarcodeOutlined, CopyOutlined } from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

interface ShelvesBarcodeProps {
  visible: boolean;
  onClose: () => void;
  shelfData: {
    id: number;
    name: string;
    code: string;
  } | null;
}

const ShelvesBarcode: React.FC<ShelvesBarcodeProps> = ({ visible, onClose, shelfData }) => {
  const barcodeRef = useRef<HTMLCanvasElement>(null);
  
  // 生成简单条形码ID格式，便于扫描
  const generateSimpleCodeString = () => {
    if (!shelfData) return '';
    return `SHELF-${shelfData.id}-${shelfData.code}`;
  };
  
  useEffect(() => {
    if (visible && shelfData) {
      try {
        // 生成条形码
        if (barcodeRef.current) {
          JsBarcode(barcodeRef.current, generateSimpleCodeString(), {
            format: "CODE128",
            width: 2,
            height: 100,
            displayValue: true,
            fontSize: 16,
            margin: 10,
            background: "#ffffff",
            lineColor: "#000000",
            text: `货架编号: ${shelfData.code}`
          });
        }
      } catch (error) {
        console.error('生成条形码失败:', error);
      }
    }
  }, [visible, shelfData]);

  const handlePrint = () => {
    if (!barcodeRef.current || !shelfData) return;
    
    const printWindow = window.open('', '_blank');
    if (printWindow) {
      const imgData = barcodeRef.current.toDataURL('image/png');
      
      printWindow.document.write(`
        <html>
          <head>
            <title>打印货架标签</title>
            <style>
              body {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100vh;
                margin: 0;
                padding: 20px;
                box-sizing: border-box;
              }
              .barcode-container {
                text-align: center;
                padding: 20px;
                border: 1px dashed #ccc;
                margin-bottom: 20px;
                max-width: 380px;
              }
              .info {
                margin-top: 10px;
                font-size: 14px;
              }
              .code-info {
                font-size: 12px;
                margin-top: 10px;
                color: #666;
                word-break: break-all;
              }
              .print-only {
                display: block;
              }
              @media print {
                button {
                  display: none;
                }
                body {
                  height: auto;
                }
              }
            </style>
          </head>
          <body>
            <div class="barcode-container">
              <div>
                <img src="${imgData}" alt="货架条形码" />
              </div>
              <div class="info">
                <p><strong>货架名称:</strong> ${shelfData.name}</p>
                <p><strong>货架编号:</strong> ${shelfData.code}</p>
              </div>
              <div class="code-info">
                <p><small>标识码: ${generateSimpleCodeString()}</small></p>
              </div>
            </div>
            <button onclick="window.print();return false;">打印</button>
          </body>
        </html>
      `);
      printWindow.document.close();
    }
  };

  const handleCopyCode = () => {
    const codeString = generateSimpleCodeString();
    navigator.clipboard.writeText(codeString)
      .then(() => {
        message.success('已复制标识码到剪贴板');
      })
      .catch(() => {
        message.error('复制失败，请手动复制');
      });
  };

  return (
    <Modal
      title="货架标签"
      open={visible}
      onCancel={onClose}
      width={500}
      footer={[
        <Button key="close" onClick={onClose}>
          关闭
        </Button>,
        <Button key="print" type="primary" onClick={handlePrint}>
          打印标签
        </Button>,
      ]}
    >
      {shelfData ? (
        <Card style={{ textAlign: 'center' }}>
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <Title level={4}>{shelfData.name}</Title>
            
            <Tabs defaultActiveKey="barcode" centered>
              <TabPane 
                tab={<span><BarcodeOutlined /> 条形码</span>}
                key="barcode"
              >
                <div style={{ border: '1px dashed #ccc', padding: '20px', backgroundColor: '#fff' }}>
                  <canvas ref={barcodeRef}></canvas>
                </div>
              </TabPane>
            </Tabs>
            
            <div>
              <Text>扫描条形码可获取货架详细信息</Text>
              <Paragraph>
                <Text type="secondary" style={{ fontSize: '12px' }}>标识码:</Text>
                <br />
                <Text code copyable style={{ wordBreak: 'break-all' }}>
                  {generateSimpleCodeString()}
                </Text>
              </Paragraph>
            </div>
            
            <Button 
              icon={<CopyOutlined />} 
              onClick={handleCopyCode}
            >
              复制标识码
            </Button>
          </Space>
        </Card>
      ) : (
        <div style={{ textAlign: 'center', padding: '30px' }}>
          <Spin />
          <div style={{ marginTop: '10px' }}>加载中...</div>
        </div>
      )}
    </Modal>
  );
};

export default ShelvesBarcode; 